/*----------------------------------------------------------------------------*\
| /gamemode/chat.lua                   | chat system                     | SRV |
\*----------------------------------------------------------------------------*/

AddCSLuaFile("shd_chat.lua")
include("shd_chat.lua")

local ChatCommands = {}

// text == Message
// color_enum = Color enumeration
// ply = player object. If you don't specify it, it will be sent to all players

function SendChatMessage(text, color_enum, ply )
	if (!ply) then
		local ply = RecipientFilter()
		ply:AddAllPlayers()
	end
	
	color_enum = color_enum or CHAT_COL_CHAT
	
	umsg.Start( "RetriveChatMessage", ply )
		umsg.String( text )
		umsg.Short( color_enum )
	umsg.End()
end

// When you add a command
// it calls like this - see the "/me" command below
// object player, string args

function AddChatCommand( cmd, func )
	local tab = {}
	
	tab.cmd = cmd
	tab.func = func
	
	table.insert(ChatCommands,tab)	
end

function GM:PlayerSay( ply, text, teamonly )
	for _,tab in ipairs(ChatCommands) do
		
		local cmd		= tab.cmd
		local cmdlen	= string.len( cmd )
		local cmdtext	= string.sub( text, 1, cmdlen + 1 )
		
		cmd				= string.Trim(string.lower( cmd ))
		cmdtext			= string.Trim(string.lower( cmdtext ))

		if (cmd == cmdtext) then
			local args = string.sub( text, cmdlen + 1 )
			if (args == nil) then
				args = ""
			end

			tab.func( ply, args )
			return ""
		end
		
	end
	
	if ( string.sub(text,1,1) == "/" )  then
		local expl = string.Explode(" ", text)	
		local cmdtext = string.sub(expl[1], 2, string.len(expl[1]))
		SendChatMessage( cmdtext .. " was not reconized as an internal or external command.", CHAT_COL_SYS, ply )
		return ""
	else
		local rf = RecipientFilter()
		
		for k,v in pairs( GetNearbyPlayers(ply:GetPos(),256) ) do
			rf:AddPlayer( v )
		end
		SendChatMessage( ply:Name() .. ": ".. text, CHAT_COL_CHAT, rf )
		return ""
	end
end

function GetNearbyPlayers( pos,size )
	local ents = ents.FindInSphere( pos,size )
	local players = {}
	
	for k,ply in ipairs(ents) do
		if ( ply:IsPlayer() && ply:Alive() ) then
			table.insert( players, ply )
		end
	end
	
	return players
end

